<template>
  <div class="product-manage">
    <div class="product-manage-form-field">
      <el-row :gutter="10" class="search-product">
        <el-col :span="10">
          <div class="grid-content bg-purple">
            <label for="product">产品名称:</label>
            <el-select
              v-model="searchData.productName"
              name="product"
              placeholder="请选择产品(可多选)"
              multiple
              filterable
              clearable
              default-first-option
              no-match-text="不存在该选项"
              size="medium"
              popper-class="b-select"
            >
              <el-option
                v-for="productItem in productOptions"
                :key="productItem.productName"
                :label="productItem.productName"
                :value="productItem.productName"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="10">
          <div class="grid-content bg-purple">
            <label for="color">产品颜色:</label>
            <el-select
              v-model="searchData.colorIds"
              name="color"
              placeholder="请选择颜色(可多选)"
              multiple
              filterable
              clearable
              default-first-option
              no-match-text="不存在该选项"
              size="medium"
              popper-class="b-select"
            >
              <el-option
                v-for="colorItem in colorOptions"
                :key="colorItem.id"
                :label="colorItem.color"
                :value="colorItem.id"
                seletced
              />
            </el-select>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="search-product">
        <el-col :span="10">
          <div class="grid-content bg-purple">
            <label for="needUpdate">产品型号:</label>
            <el-input
              v-model="searchData.productModel"
              class="w-50 m-2"
              size="large"
              placeholder="请输入需要查找的产品型号!"
              @keyup.enter.native="search"
            />
          </div>
        </el-col>
        <el-col :span="10">
          <div class="grid-content bg-purple">
            <label for="needUpdate">产品商标:</label>
            <el-input
              v-model="searchData.tradeMark"
              class="w-50 m-2"
              size="large"
              placeholder="请输入需要查找的产品商标!"
              @keyup.enter.native="search"
            />
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="add-product">
        <el-col :span="5" class="add-btn">
          <el-button type="primary" size="small" @click="search">查询</el-button>
          <el-button size="small" @click="counter++">重置</el-button>
          <el-button type="primary" plain size="small" @click="editVisible = true">添加产品</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <hr>
      </el-row>
    </div>
    <div class="product-manage-table">
      <el-table
        :data="productData"
        empty-text="暂无数据!"
        style="width: 100%"
        table-layout="fixed"
        stripe
      >
        <el-table-column align="center" prop="productName" label="产品名称" width="180">
          <template #default="scope">
            <!-- <el-tag effect="light">{{ scope.row.productName }} - {{ scope.row.color.color }}</el-tag> -->
            <el-tag effect="light">{{ scope.row.productName }}</el-tag>
            <!-- {{ scope.row.productName }} -->
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productName" label="颜色" min-width="80">
          <template #default="scope">
            <el-tag effect="light">{{ scope.row.color.color }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productModel" label="产品型号" min-width="80">
          <template #default="scope">
            {{ scope.row.productModel }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="tradeMark" label="商标" />
        <el-table-column align="center" prop="singleWeight" label="单个克数(克)" min-width="90">
          <template #default="scope">
            {{ scope.row.singleWeight }} g
          </template>
        </el-table-column>
        <el-table-column align="center" prop="oneBoxWeight" label="每盆大约重量(kg)" min-width="100">
          <template #default="scope">
            {{ scope.row.oneBoxWeight }} kg
          </template>
        </el-table-column>
        <el-table-column align="center" prop="oneBoxNumber" label="每盆大约个数(个)" min-width="100">
          <template #default="scope">
            {{ scope.row.oneBoxNumber }} 个
          </template>
        </el-table-column>
        <el-table-column align="center" prop="postscript" label="备注信息" />
        <el-table-column align="center" prop="updatedAt" label="修改日期" width="100">
          <template #default="scope">
            <div>
              {{ moment(scope.row.updatedAt).format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="updatedUser" label="修改人" min-width="80" />
        <el-table-column align="center" prop="createdAt" label="添加日期" width="100">
          <template #default="scope">
            <div>
              {{ moment(scope.row.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createdUser" label="添加人" min-width="80" />
        <el-table-column align="center" label="操作" min-width="110">
          <template #default="scope" min-width="180">
            <el-button type="primary" plain size="small" @click="updateHandle(scope.row)">修改</el-button>
            <el-button v-if="hasAdminPermission" type="danger" plain size="small" @click="deleteHandle(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="20" justify="center" align="middle" type="flex" class="page-row">
        <el-col :span="10">
          <el-pagination
            layout="total, sizes, prev, pager, next"
            :current-page="page"
            :page-size="size"
            :total="total"
            :page-sizes="[1, 5, 10, 15, 20, 30, 40, 50, 100, 500, 1000]"
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-col>
      </el-row>
    </div>
    <div class="product-manage-dialog">
      <el-dialog :title="formData.id ? '修改产品信息': '添加产品'" :visible.sync="editVisible" width="580px" top="12vh">
        <el-form :model="formData">
          <el-form-item label="产品名称:" label-width="140px">
            <el-input v-model="formData.productName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="颜色:" label-width="140px">
            <el-select
              v-if="editVisible && !formData.id"
              v-model="formData.colorIds"
              name="color"
              placeholder="颜色多选则新增多个同系列不同颜色产品"
              multiple
              filterable
              clearable
              default-first-option
              no-match-text="不存在该选项"
              size="medium"
              popper-class="b-select"
            >
              <el-option
                v-for="colorItem in colorOptions"
                :key="colorItem.id"
                :label="colorItem.color"
                :value="colorItem.id"
              />
            </el-select>
            <el-select
              v-if="editVisible && formData.id !== 0"
              v-model="formData.colorId"
              name="color"
              :placeholder="'请选择颜色'"
              filterable
              clearable
              default-first-option
              no-match-text="不存在该选项"
              size="medium"
              popper-class="b-select"
            >
              <el-option
                v-for="colorItem in colorOptions"
                :key="colorItem.id"
                :label="colorItem.color"
                :value="colorItem.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品型号:" label-width="140px">
            <el-input v-model="formData.productModel" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商标:" label-width="140px">
            <el-input v-model="formData.tradeMark" autocomplete="off" />
          </el-form-item>
          <el-form-item label="每盆大约重量(kg):" label-width="140px">
            <el-input v-model="formData.oneBoxWeight" autocomplete="off" />
          </el-form-item>
          <el-form-item label="每盆大约个数(个):" label-width="140px">
            <el-input v-model="formData.oneBoxNumber" autocomplete="off" />
          </el-form-item>
          <el-form-item label="是否热门:" label-width="140px">
            <el-switch
              v-model="formData.isHot"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              el-switch-on-color="#13ce66"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <!-- <el-form-item label="颜色名称 :" label-width="140px">
            <el-input v-model="formData.product" autocomplete="off" />
          </el-form-item> -->
          <el-form-item label="备注信息:" label-width="140px">
            <el-input v-model="formData.postscript" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">提 交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getProductList, addProduct, getProductsOptionsList, removeProduct, updateProduct } from '@/api/product'
import { getColorList } from '@/api/color'
import { adminPermissionTime } from '@/config/config'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      // 表单域数据
      productVal: '',
      postscript: '',
      searchData: {},
      productOptions: [],
      colorOptions: [],
      // 表格数据
      productData: [],
      product: '',
      total: 0,
      page: 1,
      size: 10,
      // 添加修改弹框
      editVisible: false,
      formData: { id: 0 },
      counter: 0,
      timeoutId: null,
      permissionTimeoutId: null,
      hasAdminPermission: false
    }
  },
  watch: {
    counter(newValue, oldValue) {
      clearTimeout(this.timeoutId)

      this.timeoutId = setTimeout(() => {
        this.counter = 0
      }, 10000)

      if (this.counter >= 10) {
        this.setAdminPermission()
        this.hasAdminPermission = true
        clearTimeout(this.permissionTimeoutId)
        this.permissionTimeoutId = setTimeout(() => {
          this.hasAdminPermission = false
        }, adminPermissionTime)
      }
    }
  },
  mounted() {
    this.search()
    this.initProductSelect()
    this.initColorSelect()
  },
  methods: {
    // 表单域方法
    async search() {
      const searchData = {
        ...this.searchData,
        page: this.page,
        size: this.size
      }
      try {
        const { code, data } = await getProductList(searchData)
        if (code === 200) {
          this.total = data.count
          this.productData = data.list
        }
      } catch (error) {
        Message({ type: 'error', message: '获取数据失败' })
      }
    },
    // 初始化产品下拉框数据
    async initProductSelect() {
      try {
        const { code, data } = await getProductsOptionsList()
        if (code === 200) {
          this.productOptions = data
        }
      } catch (error) {
        Message({ type: 'error', message: '获取数据失败' })
      }
    },
    // 初始化颜色下拉框数据
    async initColorSelect() {
      try {
        const { code, data } = await getColorList({ page: 1, size: 10000 })
        if (code === 200) {
          this.colorOptions = data.list
        }
      } catch (error) {
        Message({ type: 'error', message: '获取数据失败' })
      }
    },
    // 表格区域方法
    handleCurrentChange(val) {
      this.page = val
      this.search()
    },
    handleSizeChange(val) {
      this.size = val
      this.search()
    },

    async updateHandle(row) {
      this.formData = Object.assign({}, row)
      this.editVisible = true
    },

    async deleteHandle(row) {
      try {
        const { code, message } = await removeProduct({ id: row.id })
        if (code === 200) {
          Message({ type: 'success', message })
          this.search()
        }
      } catch (error) {
        Message({ type: 'error', message: '删除失败!' })
      } finally {
        this.initProductSelect()
      }
    },
    cancel() {
      this.formData = this.formData = { id: 0 }
      this.editVisible = false
    },
    async submit() {
      if (!this.formData.productModel) {
        this.formData.productModel = '-'
      }

      if (!this.formData.tradeMark) {
        this.formData.tradeMark = '-'
      }

      if (!this.formData.postscript) {
        this.formData.postscript = '-'
      }

      if (!this.formData.id) {
        try {
          const { code, message } = await addProduct(this.formData)
          if (code === 200) {
            Message({ type: 'success', message })
            this.search()
          }
        } catch (error) {
          Message({ type: 'error', message: '添加失败!' })
        } finally {
          this.editVisible = false
          this.initProductSelect()
          this.formData = { id: 0 }
        }

        return // Message({ type: 'error', message: 'id 错误!请联系系统管理员!' })
      }

      try {
        delete this.formData.updatedAt
        delete this.formData.createdAt
        const { code, message } = await updateProduct(this.formData)
        if (code === 200) {
          Message({ type: 'success', message })
          this.search()
        }
      } catch (error) {
        Message({ type: 'error', message: '修改失败!' })
      } finally {
        this.editVisible = false
        this.initProductSelect()
        this.formData = { id: 0 }
      }
    }
  }
}
</script>
<style lang="scss" scoped>

.el-row {
  margin: 18px 0;
}
label {
  margin-right: 8px;
  font-size: 14px;
}
[class*="el-col-"] {
  text-align: left;
}
.b-select {
  width: 100%;
}
.el-select {
  width: 80%;
}
.status .el-select {
  width: 60%;
}
.el-input {
    width: 70%;
    height: 36px;
  }

  ::v-deep.el-input__inner{
    height: 36px;
  }

  .add-btn{
    height: 40px;
    display: flex;
    align-items: center;
  }
.create-time .el-date-editor,
.update-time .el-date-editor {
  width: 81%;
}
.add-product,
.search-product{
  display: flex;
  align-items: center;
  .el-input {
    width: 70%;
    height: 36px;
  }

  ::v-deep.el-input__inner{
    height: 36px;
  }

  .add-btn{
    height: 40px;
    display: flex;
    align-items: center;
  }
}
.search-product{
  .el-input{
    width: 81%;
  }
}

.product-manage {
  padding: 6px 40px;
  box-sizing: border-box;
  width: 100%;
}

.el-pagination{
  display: flex;
  justify-content: center;

}

::v-deep .el-dialog__body{
  padding: 20px 10px 10px 42px;
  .el-form-item__label {
    // text-align: justify;
    // text-align-last: justify; /* 确保最后一行也两端对齐 */
    display: flex;
    flex-direction: column;
  }
  .el-select{
    width: 100%;
  }
  .el-input{
    width: 85%;
  }

  .el-switch.is-checked {
    .el-switch__core{
      border-color: #13ce66;
      background-color: #13ce66;
    }
  }

  // .el-form-item__label:before {
  //   content: '*';
  //   color: red;
  //   position: absolute;
  //   left: 0; /* 星号定位到标签最左侧 */
  //   top: 0; /* 调整垂直位置以适应行高 */
  // }

}

.dialog-footer{
  display: flex;
  justify-content: center;
}
</style>
